package com.maventools;

import com.maventools.config.DownloadConfig;
import com.maventools.config.SpringConfig;
import com.maventools.domain.Configuration;
import com.maventools.domain.Configuration.Mirror;
import com.maventools.domain.Maven;
import com.maventools.utils.InstallMavenUtils;
import com.maventools.utils.MavenVersionConverter;
import com.maventools.utils.UpdateMavenRepository;
import com.maventools.utils.XmlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.IntStream;

/**
 * @BelongsProject: maventools
 * @BelongsPackage: com.maventools
 * @Author: Layila
 * @CreateTime: 2025-05-06  17:23
 * @Description: 程序入口
 * @Version: 1.0
 * @Since:Java17
 */

@Component
public class APP {
    @Autowired
    private InstallMavenUtils imu;
    @Autowired
    private Configuration configuration;
    @Autowired
    private DownloadConfig downloadConfig;
    @Autowired
    private MavenVersionConverter mvc;
    private static List<Maven> mavenList;


    public static void main(String[] args) throws Exception {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        APP app = ctx.getBean(APP.class);  // 获取APP实例，依赖已注入
        long startTime = System.currentTimeMillis();
        while (true) {
            int menu = app.menu();
            switch (menu) {
                //选择版本并下载对应Maven版本
                case 1:
                    try {
                        mavenList = app.imu.getMavenList();
                        new MavenVersionConverter().categorizeAndPrintVersions(mavenList);
                        System.out.println("which Version would you install?");
                        String version = new Scanner(System.in).next();
                        app.imu.Installer(version, true);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    break;
                // settings.xml文件管理
                case 2: {
                    System.out.println("您安装的maven版本");
                    List<String> versions = app.mvc.getInstallVersions();
                    IntStream.range(0, versions.size()).forEach(i -> System.out.println((i + 1) + "." + versions.get(i)));
//                versions.forEach(System.out::println);   优雅输出List
                    if(versions.size()<=0){
                        break;
                    }
                    System.out.println("输入您的maven版本");
                    String version = versions.get(new Scanner(System.in).nextInt() - 1);
                    File xmlFile = new File(app.downloadConfig.getSettingPath().replace("**", "apache-maven-" + version));
                    app.configuration = XmlUtils.parseXML(xmlFile);
                    boolean  flag=true;
                    while (flag) {
                        int choice = menu1();
                        Scanner scanner = new Scanner(System.in);
                        switch (choice) {
                            case 1: { // 获取maven配置信息
                                System.out.println("您的Maven配置:");
                                System.out.println("本地仓库: " + (app.configuration.getLocalRepository() == null ? "未配置" : "已配置：" + app.configuration.getLocalRepository()));
                                System.out.println("配置集: " + (app.configuration.getPluginGroups().isEmpty() ? "未配置" : "已配置")); // 更简洁的输出
                                System.out.println("代理: " + (app.configuration.getProxies().isEmpty() ? "未配置" : "已配置"));        // 更简洁的输出
                                System.out.println("镜像:");
                                if (app.configuration.getMirrors() != null) {
                                    for (Configuration.Mirror m : app.configuration.getMirrors()) {
                                        System.out.println("  id: " + m.getId() + ", url: " + m.getUrl());
                                    }
                                } else {
                                    System.out.println("未配置");
                                }
                                System.out.println("配置完整对象信息:\n" + app.configuration);
                                break;
                            }
                            case 2: { // 修改maven配置信息
                                System.out.println("请选择要修改的配置项:");
                                System.out.println("1. 本地仓库路径");
                                System.out.println("2. 添加镜像");
                                System.out.println("3. 修改镜像");
                                System.out.println("4. 删除镜像");
                                System.out.println("5. 添加国内镜像");
                                System.out.println("0. 返回");
                                int modifyChoice = scanner.nextInt();
                                scanner.nextLine(); // Consume newline
                                switch (modifyChoice) {
                                    case 1: {
                                        System.out.println("请输入新的本地仓库路径:");
                                        String newRepo = scanner.nextLine();
                                        app.configuration.setLocalRepository(newRepo);
                                        XmlUtils.generateXML(app.configuration, xmlFile); // 使用 generateXML
                                        System.out.println("本地仓库路径已修改为: " + newRepo);
                                        break;
                                    }
                                    case 2: {
                                        System.out.println("请输入镜像的id:");
                                        String id = scanner.nextLine();
                                        System.out.println("请输入镜像的url:");
                                        String url = scanner.nextLine();
                                        System.out.println("请输入镜像的mirrorOf:");
                                        String mirrorOf = scanner.nextLine(); // 添加 mirrorOf 输入
                                        Mirror mirror = new Configuration.Mirror();
                                        mirror.setId(id);
                                        try {
                                            mirror.setUrl(new URL(url)); // URL 需要校验
                                        } catch (Exception e) {
                                            System.out.println("URL 格式不正确!");
                                            break; // URL 错误，退出
                                        }
                                        mirror.setMirrorOf(mirrorOf); // 设置  mirrorOf
                                        if (app.configuration.getMirrors() == null) {
                                            app.configuration.setMirrors(new ArrayList<>());
                                        }
                                        app.configuration.getMirrors().add(mirror);
                                        XmlUtils.generateXML(app.configuration, xmlFile); // 使用 generateXML
                                        System.out.println("镜像已添加: id=" + id + ", url=" + url + ", mirrorOf=" + mirrorOf);
                                        break;
                                    }
                                    case 3: {
                                        if (app.configuration.getMirrors() == null || app.configuration.getMirrors().isEmpty()) {
                                            System.out.println("没有镜像可以修改");
                                            break;
                                        }
                                        System.out.println("请输入要修改的镜像的id:");
                                        String id = scanner.nextLine();
                                        boolean found = false;
                                        for (Mirror mirror : app.configuration.getMirrors()) {
                                            if (mirror.getId().equals(id)) {
                                                System.out.println("请输入新的镜像url:");
                                                String newUrl = scanner.nextLine();
                                                try {
                                                    mirror.setUrl(new URL(newUrl)); // URL 需要校验
                                                } catch (Exception e) {
                                                    System.out.println("URL 格式不正确!");
                                                    break; // URL 错误，退出
                                                }
                                                XmlUtils.generateXML(app.configuration, xmlFile); // 使用 generateXML
                                                System.out.println("镜像 " + id + " 的url已修改为: " + newUrl);
                                                found = true;
                                                break;
                                            }
                                        }
                                        if (!found) {
                                            System.out.println("未找到id为 " + id + " 的镜像");
                                        }
                                        break;
                                    }
                                    case 4: {
                                        if (app.configuration.getMirrors() == null || app.configuration.getMirrors().isEmpty()) {
                                            System.out.println("没有镜像可以删除");
                                            break;
                                        }
                                        System.out.println("请输入要删除的镜像的id:");
                                        String id = scanner.nextLine();
                                        boolean removed = app.configuration.getMirrors().removeIf(mirror -> mirror.getId().equals(id)); // 使用 removeIf
                                        if (removed) {
                                            XmlUtils.generateXML(app.configuration, xmlFile); // 使用 generateXML
                                            System.out.println("镜像 " + id + " 已删除");
                                        } else {
                                            System.out.println("未找到id为 " + id + " 的镜像");
                                        }
                                        break;
                                    }
                                    case 5: {
                                        List<Mirror> mirrors = new ArrayList<>();
                                        mirrors.add(new Configuration.Mirror("aliyunmaven", "*", new URL("https://maven.aliyun.com/repository/public")));
                                        mirrors.add(new Configuration.Mirror("tencent-maven", "*", new URL("https://mirrors.cloud.tencent.com/repository/maven-public")));
                                        mirrors.add(new Configuration.Mirror("huawei-maven", "*", new URL("https://repo.huaweicloud.com/repository/maven/")));
                                        System.out.println("设置本地镜像:");
                                        IntStream.range(0,mirrors.size()).forEach(i->System.out.println((i+1)+"\t"+mirrors.get(i) ));
                                        app.configuration.getMirrors().add(mirrors.get((scanner.nextInt()-1)));
                                        XmlUtils.generateXML(app.configuration, xmlFile); // 使用 generateXML
                                        System.out.println("镜像已添加: id=" +  mirrors.get(scanner.nextInt()).getId() + ", url=" +  mirrors.get(scanner.nextInt()).getUrl());
                                    }
                                    break;
                                    case 0: {
                                        break;
                                    }
                                    default: {
                                        System.out.println("无效选项");
                                    }
                                }
                                break;
                            }
                            case 3: { // 恢复默认配置信息
                                String defaultSettingsPath = "settings.xml"; // 假设默认配置文件在resources目录下
                                File targetFile = new File(app.downloadConfig.getSettingPath().replace("**", "apache-maven-" + version));

                                try (InputStream in = APP.class.getClassLoader().getResourceAsStream(defaultSettingsPath)) {
                                    if (in == null) {
                                        System.out.println("默认配置文件未找到: " + defaultSettingsPath);
                                        break;
                                    }
                                    Files.copy(in, Paths.get(targetFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
                                    System.out.println("已恢复默认配置");
                                    app.configuration = XmlUtils.parseXML(targetFile);
                                } catch (IOException e) {
                                    System.out.println("恢复默认配置失败: " + e.getMessage());
                                }
                                break;
                            }
                            case 0:flag=false;break;
                            default:
                                System.out.println("无效选项，请重新输入");
                        }
                    }
                }
                //清理本地仓库的LastUpdated文件
                case 3: {
                    //如果并未发现本地仓库位置执行默认路径仓库
                    if (app.configuration.getLocalRepository() == null) {
                        app.configuration.setLocalRepository("C:\\Users\\" + System.getProperty("user.name") + "\\.m2\\repository");
                    }
                    UpdateMavenRepository.listDirectory(new File(app.configuration.getLocalRepository()));
                }
                break;
                case 0:
                    System.out.println("退出程序");
                    ctx.close();
                    return;
                default:
                    System.out.println("无效选项，请重新输入");
            }
            long endTime = System.currentTimeMillis();
            System.out.println("运行时间" + (endTime - startTime) + "ms");
        }
    }

    /**
     * 菜单工具类
     */
    public static int menu() {
        System.out.println("====================");
        System.out.println("=====maventools=====");
        System.out.println("====================");
        System.out.println("1.下载安装Maven列表");
        System.out.println("2.settings.xml文件");
        System.out.println("3.清理本地仓库的LastUpdated文件");
        System.out.println("0.退出");
        return new Scanner(System.in).nextInt();
    }

    /**
     * setting.xml文件二级菜单
     */
    public static int menu1() {
        System.out.println("====================");
        System.out.println("=====setting.xml=====");
        System.out.println("====================");
        System.out.println("1.获取maven配置信息");
        System.out.println("2.修改maven配置信息");
        System.out.println("3.恢复默认配置信息");
        System.out.println("0.返回上一级目录");
        return new Scanner(System.in).nextInt();
    }
}